package com.weiiew.calculationService.controller;

import com.weiiew.calculationService.service.CalculationServiceImpl;
import com.weiiew.common.entity.factory.Factory;
import com.weiiew.common.utils.ApiResponse;
import com.weiiew.common.exception.LockItemException;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Description
 * @Author 魏锴
 * @Date 2024/9/11
 */
@RestController
@RequiredArgsConstructor
public class CalculationController {
    private final CalculationServiceImpl calculationService;

    /**
     * 根据前端返回的工厂数据计算合成列表
     *
     * @param factory 工厂信息
     * @param version 版本号
     * @return 计算结果
     */
    @RequestMapping("/calculation")
    public ApiResponse calculation(@RequestBody Factory factory, @RequestHeader("my-version") Integer version) {
        if (factory == null || version == null) return ApiResponse.failure("参数错误");
        try{
            return ApiResponse.ok("graph", calculationService.calculation(factory, version));
        } catch (LockItemException e) {
            return ApiResponse.failure(e.toString());
        } catch (IllegalStateException e){
            return ApiResponse.failure(e.getMessage());
        } catch (Exception e){
            e.printStackTrace();
            return ApiResponse.failure("合成中存在自指循环");
        }
    }
}